const db = require('../Mysql/sql')
const dayjs = require('dayjs')
//token密钥
const jwt = require('jsonwebtoken') //加密token
const configAll = require('../../configuration.js') //公共配置
const bcryptjs = require('bcryptjs') //加密
const {
	tree,
	getIds
} = require("../../utils/common.js")
const user = {
	login(req, res) {
		let userInfo = req.body
		const sql = `select * from users where account=?`
		db.query(sql, userInfo.account, (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) return res.cc('没有该账户')
			const compare = bcryptjs.compareSync(userInfo.password, results[0].password) //数据库对比加密后的密码
			if (!compare) return res.cc('账号或密码错误')
			//加密token
			let {
				password,
				...newUserInfo
			} = results[0]
			const token = jwt.sign(newUserInfo, configAll.secreKey, {
				expiresIn: '24h'
			})
			res.send({
				status: 200,
				msg: '登录成功',
				token: 'Bearer ' + token,
				data: newUserInfo
			})
		})
	},
	//注册
	logon(req, res) {
		let userInfo = req.body
		//获取导航
		const sql3 = `select * from navigation`
		//判断是否占用
		const sql = `select * from users where account=?` //查重
		const sql2 = `insert into users set ?` //注册
		db.query(sql3, [], (err3, results3) => {
			if (err3) return res.cc(err3)
			let newArr = tree(results3, 'nid', 'fid')
			newArr = newArr.filter(v => v.key !== '/basicSettings')
			userInfo.auth = getIds(newArr)
			db.query(sql, userInfo.account, (err, results) => {
				if (err) return res.cc(err)
				if (results.length) return res.cc('已存在该账号')
				userInfo.password = bcryptjs.hashSync(userInfo.password, 10)
				userInfo.createtime = dayjs().format('YYYY-MM-DD HH:mm:ss')
				//注册
				db.query(sql2, userInfo, (err, results) => {
					if (err) return res.cc(err.message)
					if (results.affectedRows !== 1) return res.cc('注册失败')
					res.cc('注册成功', 200)
				})
			})
		})
	},
	//注销用户
	logOff(req, res) {
		let sql = `delete from users where userid=?`
		db.query(sql, req.body.userid, (err, results) => {
			if (err) return res.cc(err.message)
			if (results.affectedRows !== 1) return res.cc('注销失败')
			res.cc('注销成功', 200)
		})
	},
	//判断是否设置支付密码
	checkUserPaymentPwd(req, res) {
		const sql =
			`select if(payment_pwd,true,false) ischek from users where userid=${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) return res.cc('获取失败')
			res.send({
				status: 200,
				msg: '获取成功',
				data: results[0].ischek ? true : false
			})
		})
	},
	//判断支付金额是否输入错误
	checkUserPaymentPwdInput(req, res) {
		const sql =
			`select if(payment_pwd = ${req.body.payment_pwd},true,false) ischek from users where userid=${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) return res.cc('获取失败')
			res.send({
				status: 200,
				msg: '获取成功',
				data: results[0].ischek ? true : false
			})
		})
	},
	getUsersList(req, res) {
		let body = req.query
		let {
			pageSize,
			page
		} = body //过滤分页
		pageSize = Number(body.pageSize) || 10
		page = page == 1 ? 0 : ((body.page - 1) * pageSize)
		const sql = `select userid,username,account,sign,createtime,email,handimg,sex,birthday,hometown,bgc,balance,auth
		from users ${body.searchValue?`where username like '%${body.searchValue}%'
		or account like '%${body.searchValue}%'`:''}
		order by createtime desc limit ?,?`
		const sql2 = `select count(*) as total from users ${body.searchValue?`where username like '%${body.searchValue}%'
		or account like '%${body.searchValue}%'`:''}`
		db.query(sql2, [page, pageSize], (err, results) => {
			if (err) return res.cc(err)
			db.query(sql, [page, pageSize], (err, results2) => {
				if (err) return res.cc(err)
				if (!results[0].total) return res.send({
					status: 200,
					msg: '获取成功',
					data: [],
					total: results[0].total
				})
				res.send({
					status: 200,
					msg: '获取成功',
					data: results2,
					total: results[0].total
				})
			})
		})

	},
	//根据id获取用户信息
	getUserInfo(req, res) {
		const body = req.query
		let userid = body.userid ? body.userid : req.auth.userid
		const sql = `select * from users where userid=${userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) return res.cc('获取用户信息失败')
			let {
				password,
				payment_pwd,
				...newUserInfo
			} = results[0]
			res.send({
				status: 200,
				msg: '获取成功',
				data: newUserInfo
			})
		})
	},
	//根据id更新用户信息
	updataUserInfo(req, res) {
		let userInfo = req.body
		let userid = userInfo.userid ? userInfo.userid : req.auth.userid
		let sql = `update users set ? where userid=${userid}`
		db.query(sql, userInfo, (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('用户更新失败')
			res.cc('更新成功', 200)
		})
	},
	rechargeMoney(req, res) {
		let userInfo = req.body
		let sql = `update users set balance=balance+${req.body.balance} where userid=${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) return res.cc('充值失败')
			res.cc('充值成功', 200)
		})
	},
	//重置密码
	resetPassword(req, res) {
		let pwd = req.body
		const sql = `select * from users where userid=?`
		const sql2 = `update users set password=? where userid=?`
		db.query(sql, req.auth.userid, (err, results) => {
			if (err) return res.cc(err)
			if (results.length !== 1) return res.cc('用户不存在')
			const changePwd = bcryptjs.compareSync(pwd.oldPwd, results[0].password)
			if (!changePwd) return res.cc('原密码不匹配')
			const newPwd = bcryptjs.hashSync(pwd.newPwd, 10)
			db.query(sql2, [newPwd, req.auth.userid], (err, results) => {
				if (err) return res.cc(err)
				if (results.affectedRows !== 1) return res.cc('修改失败')
				res.cc('修改成功', 200)
			})

		})

	},

	//更新头像
	updateHeadImg(req, res) {

		const sql = 'update users set handimg=? where userid=?'
		db.query(sql, [req.body.handimg, req.auth.userid], (err, results) => {
			if (err) return res.cc(err)
			if (results.affectedRows !== 1) res.cc('更新失败')
			res.cc('更新成功', 200)
		})

	},
	//查询用户表并判断是否互关
	//我的关注
	getUserList(req, res) {
		let body = req.body
		let sql = ''
		let name = Object.keys(req.body)[0]
		let userid = body.userid ? body.userid : req.auth.userid
		if (body.type === 1) { //我的关注
			sql =
				`select f.fanid,f.id fid,f.nickname,f.isOverhead,u.* from (select * from follow where fanid = ${userid}) f left join users u on u.userid=f.userid`
		} else if (body.type === 2) { //我的粉丝
			sql =
				`select u.*,f.userid fanid,f.id fid,f.nickname,f.isOverhead from users u join follow f on u.userid = f.fanid where f.userid=${userid}`
		} else if (body.type === 3) { //我未关注的 
			sql = `select * from (select * from follow where fanid = ${userid}) f right join
			users u on u.userid=f.userid where f.userid is null and u.userid!=${userid} and u.${name}
			like '%${body.username}%'`
		} else if (body.type === 4) { //群邀请用户
			sql = `select u.userid,u.username,u.handimg,
			if( u.userid in (select c.userid from crowd_menber c where c.crowd_id = ${req.body.crowd_id}),true,false) isyq
			from users u`
		} else if (body.type === 5) { //获取关注、粉丝列表
			sql = `select a.*,if(${req.auth.userid} in (select f.fanid from follow f where a.fanid = ${req.auth.userid}),true,false) as isgz
			from (select u.*,f.userid fuserid,f.fanid,f.id fid,f.nickname,f.isOverhead 
			from users u join follow f on u.userid = f.fanid where f.userid=${userid}
			UNION all
			select u.*,f.userid fuserid,f.fanid,f.id fid,f.nickname,f.isOverhead 
			from (select * from follow where fanid = ${userid}) f left join users u on u.userid=f.userid
			) a ${req.body.fid?`where a.fid = ${req.body.fid}`:`GROUP BY a.userid`}`
		} else { //全部用户
			sql = `select * from users where userid!=${req.auth.userid} and ${name} like '%${body.username}%'`
		}

		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			for (let i in results) {
				delete results[i].password
				delete results[i].payment_pwd
			}
			res.send({
				status: 200,
				data: results,
				msg: '获取成功'
			})
		})
	},

	//获取微博、关注、粉丝 数量
	getUserDetial(req, res) {
		let userid = req.body.userid ? req.body.userid : req.auth.userid
		//获取关注数量
		let sql =
			`select count(*) as count from (select * from follow where fanid = ${userid}) f left join users u on u.userid=f.userid`
		let sql2 =
			`select count(*) as count from users join follow on users.userid = follow.fanid where follow.userid=${userid}`
		let sql3 = `select count(*) as count from article,users where authorid = userid and userid = ${userid}`

		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			db.query(sql2, [], (err2, results2) => {
				if (err2) return res.cc(err2)
				db.query(sql3, [], (err3, results3) => {
					if (err3) return res.cc(err3)
					res.send({
						status: 200,
						msg: '获取成功',
						data: {
							followNum: results[0].count,
							fanNum: results2[0].count,
							articleNum: results3[0].count
						},
					})
				})
			})
		})
	}
}

module.exports = user